#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：大路网网格化仿真
@File ：数据处理.py
@IDE ：PyCharm
@Author ：xinyingjie
@Date ：2025/2/8 11:14
'''
import json
import pandas as pd


from datetime import datetime, timezone

def get_time_second(time_str):
    dt = datetime.strptime(time_str, '%H:%M:%S')

    return dt

def get_time_day(time_str):
    dt = datetime.strptime(time_str, '%Y-%m-%d')
    # 将本地时间转换为 UTC 时间
    dt_utc = dt.astimezone(timezone.utc)
    # 将 datetime 对象转换为时间戳
    timestamp = int(dt_utc.timestamp())
    return timestamp



# 读取Excel文件
file_path = r'C:\Users\xinyingjie\Downloads\jida_event.xlsx'  # 替换为你的文件路径


# 使用 read_excel 函数读取数据
df = pd.read_excel(file_path)

# 打印每一行的数据
result = {}
for index, row in df.iterrows():
    data = row.to_dict()
    target_data = {"updateTime":data['updateTime'],"secLevel":data['secLevel'],"orgCode":data['orgCode']}
    day = data['updateTime'].split(" ")[0]

    orgCode = data['orgCode']
    if day not in result.keys():
        result[day] = {}
        result[day][orgCode] = [target_data]
    else:
        if orgCode not in result[day].keys():
            result[day][orgCode] = [target_data]
        else:
            result[day][orgCode].append(target_data)
    # print(result)
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from datetime import datetime, timedelta

# 计算时间点位置
start_time = datetime.strptime("00:00:00", "%H:%M:%S")
end_time = datetime.strptime("23:59:59", "%H:%M:%S")

# 将时间转换为相对于起始时间的分钟数，用于定位
start_min = 0
# target_min = (target_time - start_time).total_seconds() / 60
end_min = (end_time - start_time).total_seconds() / 60
color_dict = {2:"cyan",3:"yellow",4:"orange",5:"red"}
for day,org_info in result.items():


    for org,data_list in org_info.items():
        print(day,org,"================")
        fig, ax = plt.subplots(figsize=(15, 2))
        # 绘制全绿的条形图
        ax.add_patch(patches.Rectangle((start_min, 0), end_min - start_min, 1, color='green'))
        level_dict = {}
        # 设置画布

        for data in data_list:
            secLevel = data['secLevel']
            time_str = data['updateTime']

        #     # 将 datetime 对象转换为时间戳
            timestamp = get_time_second(time_str.split(" ")[1])
            # 在10:10位置添加宽度为1分钟的红色部分
            red_start = (timestamp - start_time).total_seconds() / 60
            red_width = 1  # 红色部分宽度，单位是分钟
            ax.add_patch(patches.Rectangle((red_start, 0), red_width, 1, color=color_dict[int(secLevel)]))
        # 配置x轴
        plt.xlim([start_min, end_min])
        plt.xticks([i * 60 for i in range(25)], [f'{i:02d}:00' for i in range(25)])
        plt.xlabel('Time')

        # 移除y轴和顶部、右侧边框
        ax.yaxis.set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['left'].set_visible(False)
        save_name = str(day) + "_" + str(org) + ".png"
        # plt.show()
        plt.savefig('./png/' + save_name, dpi=300, bbox_inches='tight',
                    transparent=False)
        plt.close()

        #     # print(f"本地时间 {time_str} 对应的时间戳是: {timestamp}")
        #     index = int((timestamp - start_time) / (24 * 6 * 6))
        #
        #     if secLevel not in level_dict.keys():
        #         level_dict[secLevel] = [index]
        #     else:
        #         level_dict[secLevel].append(index)
        # print(level_dict)
        # for level_key,index_list in level_dict.items():
        #     for i in range(len(index_list)- 1):
        #         if abs(index_list[i+1] - index_list[i]) <=5:




